package com.situ.staff.employee.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.situ.staff.employee.model.EmployeeModel;
import com.situ.staff.employee.service.Impl.EmployeeServiceImpl;
import com.situ.staff.util.FmtRequest;
import com.situ.staff.util.Upload;

/**
 * Servlet implementation class employeeUploadServlet
 */
@WebServlet("/employeeUploadServlet")
public class employeeUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	EmployeeServiceImpl service = new EmployeeServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			Map<String, Object> map = null;
			try {
				map = Upload.upload(request);
			} catch (FileUploadException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			List<String> list = (List<String>) map.get("list");
			String image =list.get(0);
			String code = (String) map.get("code");
			EmployeeModel model = new EmployeeModel(code);
			model.setImage(image);
			Map<String, String> result = new HashMap<String, String>();
			try {
				String res = service.update(model);
				result.put("code",res);
				result.put("image",image);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			FmtRequest.write(response.getWriter(),result );
	}

	public void upload(HttpServletRequest request) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		List<String> names = new ArrayList<String>();
		Map<String, Object> map = new HashMap<String, Object>();
		int i =1;
		for (FileItem item : items) {
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				map.put(name, value);
			} else {
//				System.out.println(item.getFieldName()+"  "+item.getName());
				String fn = getFName(item);
				FileOutputStream fw = new FileOutputStream(getFPath()+"/"+fn);//注意这里的路径拼接，要有斜杠
				byte[] b = new byte[1024*1024];
				int length =-1;
				InputStream is = item.getInputStream();
				while(-1!=(length=is.read(b))) {
					fw.write(b,0,length);
				}
				fw.flush();
				fw.close();
				is.close();
				names.add(fn);
				request.setAttribute("fn"+i++, "/images/"+fn);//images为tomcat中配置的虚拟路径
			}
		}
		map.put("list", names);
	}
	private String getFName(FileItem item) {
		// TODO Auto-generated method stub
		String fn = item.getName();
		fn = UUID.randomUUID().toString()+fn.substring(fn.indexOf("."));
		
		return fn;
	}
	
	private static File getFPath() {
		File f = new File("F:/web_workspace/imgs");
		if(!f.exists()) {
			f.mkdir();
		}
		return f;
	}
}
